package com.kreao.korean.controller;

import com.kreao.korean.dto.ApiResponse;
import com.kreao.korean.entity.User;
import com.kreao.korean.security.UserPrincipal;
import com.kreao.korean.service.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class UserController {
    
    private final UserServiceImpl userService;
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            User user = userService.getUserById(userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success(user));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取用户信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新用户资料
     */
    @PutMapping("/me")
    public ResponseEntity<?> updateProfile(
            @RequestBody User userRequest,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            User updatedUser = userService.updateUser(userPrincipal.getId(), userRequest);
            return ResponseEntity.ok(ApiResponse.success("用户资料更新成功", updatedUser));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("用户资料更新失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取用户学习概况
     */
    @GetMapping("/me/overview")
    public ResponseEntity<?> getUserOverview(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            Object overview = userService.getUserOverview(userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success(overview));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取用户概况失败: " + e.getMessage()));
        }
    }
} 